import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../models/order_detail_model.dart';
import '../../services/logger_service.dart';
import '../view/detail_top_view.dart';
import '../../components/loading_widget.dart';
import '../view/detail_bottom_view.dart';
import '../view/detail_czinfo_view.dart';
import '../view/detail_pcinfo_view.dart';
import '../view/detail_orderinfo_view.dart';
import '../../main.dart';
import '../../class/controller/product_detail.dart';
import '../controller/order_pay.dart';
import '../view/detail_cancel_view.dart';
import '../../components/toast_utils.dart';
import '../../manger/user_manger.dart';
import '../view/detail_lottery_view.dart';
import '../../manger/qysdk_manger.dart';
import '../view/detail_cardinfo_view.dart';
class OrderDetailPage extends StatefulWidget {
  final String orderId;
  const OrderDetailPage({super.key,required this.orderId});

  @override
  State<OrderDetailPage> createState() => _OrderDetailPageState();
}

class _OrderDetailPageState extends State<OrderDetailPage> {
  final ValueNotifier<bool> loadingNotifier = ValueNotifier(false);

  DetailInfoModel? _model;

  void _navigateToProductDetail(int spuId) {
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(
        builder: (context) => ProductDetailPage(spuId: spuId),
      ),
      (route) => route.isFirst,
    );
  }


  Future<void> _fetchOrderDetails() async {
    if (loadingNotifier.value) return; // 如果正在加载，则不重复加载
    loadingNotifier.value = true;
    final response = await NetworkUtils.post(
      RequestCmd.detail,
      body: {'orderId': widget.orderId,"token": UserInfos.shared.productToken},
      loadingNotifier: loadingNotifier,
    );
    final model = OrderDetailModel.fromJson(response);
    if (UserInfos.shared.productToken.isNotEmpty){
      UserInfos.shared.productToken = "";
    }
    if (model.code == 200) {
      setState(() {
        _model = model.data;
      });

      if (model.data?.activity != null && mounted) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) => LotteryDrawView(model: model.data!.activity!),
        );
      }
    } else {
    }

    loadingNotifier.value = false;
  }

  @override
  void initState() {
    super.initState();
    _fetchOrderDetails();
  }

  Future<List<Map<String, dynamic>>> _parseAttrs(String attrs) async {
    try {
      final decoded = json.decode(attrs) as List;
      return decoded.map<Map<String, dynamic>>((item) {
        if (item is Map<String, dynamic>) {
          return item;
        }
        return {};
      }).toList();
    } catch (e) {
      return [];
    }
  }

  void _goToOrderPage() {
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(
        builder: (_) => MainPage(initialIndex: 3), // 1 表示 OrderPage 所在的 tab 索引
      ),
      (route) => false,
    );
  }

  void cancelOrder() async {
    showModalBottomSheet(
      context: context,
      builder: (context) => DetailCancelView(
        onReasonSelected: (reason) {
          cancelOrderNext(reason);
        },
      ),
    );
  }

  void cancelOrderNext(String reson) async {
    try {
      final response = await NetworkUtils.post(
        RequestCmd.cancel,
        body: {"orderId": widget.orderId, "closeType": reson},
      );
      if (response != null && response['code'] == 200) {
        // _goToOrderPage();
        ToastUtils.showCenterToast(context, response['msg']);
        _fetchOrderDetails();
      } else {
        ToastUtils.showCenterToast(context, response['msg']);
      }
    } catch (e) {
      print(e);
    }
  }

@override
Widget build(BuildContext context) {
  return PopScope(
    canPop: false,
    onPopInvokedWithResult: (didPop, result) {
      if (!didPop) {
        _goToOrderPage();
      }
    },
    child: Scaffold(
      bottomNavigationBar: _model == null
          ? null
          : DetailBottomView(
              model: _model!,
              onPay: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => OrderPayPage(orderId: widget.orderId, spuId: _model!.spuId),
                  ),
                );
              },
              onCustom: () {
                // TODO: 实现客服逻辑
                QYSDK.showQYSession();  
              },
              onCancel: () {
                // TODO: 实现取消订单逻辑
                cancelOrder();
              },
              onReorder: () {
                _navigateToProductDetail(_model!.spuId);
              },
            ),
      appBar: AppBar(
        toolbarHeight: 40,
        leading: IconButton(
          icon: Image.asset('assets/images/leftpush.png'),
          onPressed: _goToOrderPage,
        ),
        title: Text(
          AppLocalizations.of(context)!.orderDetails,
          style: const TextStyle(fontSize: 17),
        ),
      ),
      body: ValueListenableBuilder<bool>(
        valueListenable: loadingNotifier,
        builder: (context, isLoading, child) {
          if (_model == null) {
            return LoadingWidget(isLoading: loadingNotifier);
          }
          return SingleChildScrollView(
            child: Column(
              children: [
                DetailTopView(
                  model: _model!,
                  onGoPay: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => OrderPayPage(orderId: widget.orderId, spuId: _model!.spuId),
                      ),
                    );
                  },
                  localizations: AppLocalizations.of(context)!,
                ),
                if (_model!.attrs.isNotEmpty)
                  FutureBuilder<List<Map<String, dynamic>>>(
                    future: _parseAttrs(_model!.attrs),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return DetailCzInfoView(
                          models: snapshot.data!,
                          isScuuessPass: true,
                        );
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                if (_model!.cardsInfo.isNotEmpty && _model!.rechargeType == 2)
                DetailCardInfoView(
                  cardInfo: _model!.cardsInfo,  // 传入卡密信息
                  onToggleExpand: (bool isExpanded) {
                    // 处理展开/收起状态变化
                  },
                ),
                GestureDetector(
                  onTap: () => _navigateToProductDetail(_model!.spuId),
                  child: DetailPcInfoView(model: _model!),
                ),
                DetailOrderInfoView(model: _model!),
              ],
            ),
          );
        },
      ),
    ),
  );
}


}